#!/usr/bin/env python3
# This file a part of SHM. Copyright (C) Tom Li 2013.
# License: LGPL version 3 or later.


from configparser import ConfigParser


class Config():
    def __init__(self, path, user=None):
        self._config = ConfigParser()
        self._config.read(path)

        if not self._config.has_section('users'):
            self._config['users'] = {}
        self.user = user

        self._open = True
        self._path = path

    @property
    def domain(self):
        try:
            return eval(self._config['users'][self.user])
        except KeyError:
            self._config['users'][self.user] = str([])
            return eval(self._config['users'][self.user])

    @domain.setter
    def domain(self, domain):
        self._config['users'][self.user] = str(domain)

    def append_domain(self, domain):
        if domain in self.domain:
            return
        new_domain_list = self.domain
        new_domain_list.append(domain)
        self.domain = new_domain_list

    def remove_domain(self, domain):
        if domain not in self.domain:
            return
        new_domain_list = self.domain
        new_domain_list.remove(domain)
        self.domain = new_domain_list

    def save(self):
        if not self._open:
            return
        with open(self._path, "w+") as config_file:
            self._config.write(config_file)
        self._open = False

    def __del__(self):
        self.save()
